// const path = require('path')

const isProd = process.env.NODE_ENV === 'production'

const BrotliPlugin = require('brotli-webpack-plugin')
// const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css', 'png', 'jpeg']

/** cdn加速 **/
const cdn = {
  // cdn：模块名称和模块作用域命名（对应window里面挂载的变量名称）
  externals: {
    'axios': 'axios'
  },
  // cdn的css链接
  css: [
    ''
  ],
  // cdn的js链接
  js: [
    'https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js'
  ]
}

module.exports = {
  publicPath: './', // 打包时配置，部署成功后，可访问到index.html
  lintOnSave: false,
  productionSourceMap: false, // 是否在构建生产包时生成sourcdeMap
  css: { // 设置公共CSS样式文件 css预设器配置项 详见https://cli.vuejs.org/zh/config/#css-loaderoptions
    loaderOptions: {
      scss: {
        prependData: `@import "./src/assets/styles/index.scss";`
      }
    }
  },
  chainWebpack: config => {
    if (isProd) {
      // 规则参考 https://cli.vuejs.org/zh/guide/webpack.html
      /*** 图片压缩 ***/
      // config.module
      //   .rule('images')
      //   .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
      //   .use('image-webpack-loader')
      //   .loader('image-webpack-loader')
      //   .options({
      //     mozjpeg: {
      //       progressive: true,
      //       quality: 65
      //     },
      //     optipng: {
      //       enabled: false
      //     },
      //     pngquant: {
      //       quality: [0.65, 0.9],
      //       speed: 4
      //     },
      //     gifsicle: {
      //       interlaced: false
      //     }
      //   }).end()

      /** cdn 注入 **/
      config.plugin('html').tap(args => {
        args[0].cdn = cdn
        return args
      })
    }
  },
  configureWebpack: config => {
    if (isProd) {
      /*** gzip压缩机制 ***/
      // config.plugins.push(new CompressionWebpackPlugin({
      //   asset: '[path].gz[query]',
      //   algorithm: 'gzip',
      //   test: new RegExp(`\\.('${productionGzipExtensions.join('|')}')$`),
      //   threshold: 10240,
      //   minRatio: 0.8
      // }))
      // config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
      /*** 
      br压缩机制 
      (Brotli是最初由Google开发的一种压缩算法，其压缩性能优于gzip。node11.7.0及更高版本在其zlib模块中具有对Brotli压缩的支持，相对gzip压缩提高20%。)
      ngnix 开启 Brotli https://www.mf8.biz/nginx-brotli-better-than-gzip-compression/
      ***/
      config.plugins.push(new BrotliPlugin({
        asset: '[path].br[query]',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240,
        minRatio: 0.8
      }))
      /** 用cdn方式引入，则构建时要忽略相关资源 **/
      config.externals = cdn.externals
      /*** 公共代码抽离 ***/
      config.optimization = {
        splitChunks: {
          cacheGroups: {
            vendor: {
              chunks: 'all',
              test: /node_modules/,
              name: 'vendor',
              minChunks: 1,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 100
            },
            common: {
              chunks: 'all',
              test: /[\\/]src[\\/]js[\\/]/,
              name: 'common',
              minChunks: 2,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 60
            },
            styles: {
              name: 'styles',
              test: /\.(sa|sc|c)ss$/,
              chunks: 'all',
              enforce: true
            },
            runtimeChunk: {
              name: 'manifest'
            }
          }
        }
      }
      /*** 配置分离第三方库 ***/
      config.optimization = {
        splitChunks: {
          chunks: 'all',
          minSize: 1, // 模块的最小体积
          minChunks: 1, // 模块的最小被引用次数
          maxAsyncRequests: 20, // 按需加载的最大并行请求数
          maxInitialRequests: 20, // 一个入口最大并行请求数
          cacheGroups: { // 缓存组
            vue: {
              name: 'os-vue',
              test: /[\\/]node_modules[\\/]vue[\\/]/,
              priority: 20
            },
            vuex: {
              name: 'os-vuex',
              test: /[\\/]node_modules[\\/]vuex[\\/]/,
              priority: 19
            },
            axios: {
              name: 'os-axios',
              test: /[\\/]node_modules[\\/]axios[\\/]/,
              priority: 18
            },
            'vue-router': {
              name: 'os-router',
              test: /[\\/]node_modules[\\/]vue-router[\\/]/,
              priority: 17
            },
            'element-plus': {
              name: 'os-element',
              test: /[\\/]node_modules[\\/]element-plus[\\/]/,
              priority: 16
            }
          }
        }
      }
    }
  },
  devServer: {
    open: true, // 默认打开的浏览器
    port: 8090, // 端口号
    hotOnly: true, // 热加载
    proxy: { // 跨域配置
      '/api': { // 过滤的api
        target: 'http://10.32.40.16:8082', // 要访问的URL
        changeOrigin: true, // true，启用跨域
        pathRewrite: { // 要转发到的地址，根据需要也可不配置

        }
      }
    }
  }
}